package database

import (
	"fmt"
	"hxy/repo/cmd"
	"hxy/repo/model"

	"hxy/repo/config"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var Db *gorm.DB

func GetConnect() *gorm.DB {

	return Db
}

// 初始化Database连接
// 放在init函数中跟随包的引入被call，在损失一定可控性的情况下保证连接的可用性
func init() {
	if Db != nil {
		return
	}
	var err error
	Db, err = gorm.Open(sqlite.Open(config.Sqlfile), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
	}
	sqlDB, err := Db.DB()
	if err != nil {
		fmt.Println(err)
	}
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	Db.AutoMigrate(&model.GitModel{})
	Db.AutoMigrate(&model.GitAuth{})
	Db.AutoMigrate(&model.GitMonitorInter{})
	Db.AutoMigrate(&cmd.PipelineTask{})
	Db.AutoMigrate(&model.DockerImageBuilder{})
	Db.Where("1 = 1").Delete(&model.GitMonitorInter{})

}
